define("login", ["jquery.validate-cn", "jquery.ui", "bootstrap", "md5"], function() {

	"use strict";
	var hascookie = false;
	var usr = "";
	var pwd = "";

	return {
		init: function(skip) {
			$('.login-form').validate({
				errorElement: 'span',
				errorClass: 'help-block',
				focusInvalid: false,
				rules: {
					username: {
						required: true
					},
					password: {
						required: true
					},
					remember: {
						required: false
					}
				},

				messages: {
					username: {
						required: "请输入用户名"
					},
					password: {
						required: "请输入密码"
					}
				},

				invalidHandler: function(event, validator) {
					$('.alert-danger', $('.login-form')).show();
				},

				highlight: function(element) {
					$(element).closest('.form-group').addClass('has-error');
				},

				success: function(label) {
					label.closest('.form-group').removeClass('has-error');
					label.remove();
				},

				errorPlacement: function(error, element) {
					error.insertAfter(element);
				},

				submitHandler: function(form) {
					usr = $("input[name = 'username']").val();
					pwd = $("input[name = 'password']").val();
					if(!hascookie) {
						pwd = hex_md5(pwd);
					}
					if(!$("#check-remember").prop("checked")) {
						vw_static.delCookie("remember");
					}
					login(skip);
				}
			});

			$("input[name = 'username']").change(function(e) {
				vw_static.delCookie("remember");
				$("#check-remember").prop("checked", false);
				$("input[name = 'password']").val("");
				hascookie = false;
			});
			$("input[name = 'password']").change(function(e) {
				vw_static.delCookie("remember");
				hascookie = false;
			});

			$('.forget-form').validate({
				errorElement: 'span',
				errorClass: 'help-block',
				focusInvalid: false,
				ignore: "",
				rules: {
					email: {
						required: true,
						email: true
					}
				},
				messages: {
					email: {
						required: "请输入电子邮件地址"
					}
				},
				invalidHandler: function(event, validator) { //display error alert on form submit  
				},
				highlight: function(element) { // hightlight error inputs
					$(element).closest('.form-group').addClass('has-error');
				},
				success: function(label) {
					label.closest('.form-group').removeClass('has-error');
					label.remove();
				},
				errorPlacement: function(error, element) {
					error.insertAfter(element);
				},
				submitHandler: function(form) {
					$('.alert-reset-error', $('.forget-form')).hide();
					ResetPwd($("input[name = 'email']").val());
				}
			});

			$('#forget-password').click(function() {
				$('.login-form').hide();
				$('.forget-form').show();
				$('.alert-reset-ok', $('.forget-form')).hide();
				$('.alert-reset-error', $('.forget-form')).hide();
				$("input[name = 'email']").val("");
			});

			$('#back-btn').click(function() {
				$('.login-form').show();
				$('.forget-form').hide();
			});

			$('.register-form').validate({
				errorElement: 'span',
				errorClass: 'help-block',
				focusInvalid: false,
				ignore: "",
				rules: {
					username1: {
						required: true,
						remote: {
							url: VW_INTERFACE.WEBSERVICE.LoginManage("UserIsExsit"),
							data: {
								userName: function() {
									return $("input[name = 'username1']").val();
								}
							}
						}
					},
					password1: {
						required: true,
						minlength: 6,
						regexPassword: true
					},
					rpassword1: {
						equalTo: "#register_password"
					},
					email1: {
						required: true,
						email: true,
						remote: {
							url: VW_INTERFACE.WEBSERVICE.LoginManage("EmailIsExsit"),
							data: {
								email: function() {
									return $("input[name = 'email1']").val();
								}
							}
						}
					},
					tnc: {
						required: true
					}
				},
				messages: {
					username1: {
						remote: "该用户名已存在！"
					},
					email1: {
						remote: "该邮箱已注册！"
					},
					password1: {
						regexPassword: "必须包含至少一位数字和一位字母"
					}
				},
				invalidHandler: function(event, validator) {},
				highlight: function(element) {
					$(element).closest('.form-group').addClass('has-error');
				},
				success: function(label) {
					label.closest('.form-group').removeClass('has-error');
					label.remove();
				},
				errorPlacement: function(error, element) {
					error.insertAfter(element);
				},
				submitHandler: function(form) {
					registUser($("input[name = 'username1']").val(), $("input[name = 'password1']").val(), $("input[name = 'email1']").val());
				}
			});

			jQuery.validator.addMethod("regexPassword", function(value, element) {
				var regexPassword = /^(?![^a-zA-Z]+$)(?!\D+$)/;
				return this.optional(element) || (regexPassword.test(value));
			}, "必须包含至少一位数字和一位字母");

			$('#register-btn').click(function() {
				jQuery('.login-form').hide();
				jQuery('.register-form').show();
				$("input[name = 'username1']").val('');
				$("input[name = 'password1']").val('');
				$("input[name = 'email1']").val("");
			});

			$('#register-back-btn').click(function() {
				jQuery('.login-form').show();
				jQuery('.register-form').hide();
				$("input[name = 'username']").val('');
				$("input[name = 'password']").val('');
			});

			//选择进入的平台页，点击返回按钮，回到登录页
			$('#select-back-btn').click(function() {
				$('.login-form').show();
				$('.select-form').hide();
			});

			var r = vw_static.getCookie("remember");
			if(r) {
				hascookie = true;
				usr = r.split('|')[0];
				pwd = r.split('|')[1];
				$("input[name = 'username']").val(usr);
				$("input[name = 'password']").val(pwd);
				$("#check-remember").prop("checked", true);
			}
		},

		//暴露给界面中选择平台按钮调用
		selectuser: function(value) {
			submitLogin(vw_static.hashMap.Get(value));
		}
	};

	function login(_skip) {
		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.LoginManage("UserLogin"),
			type: "GET",
			dataType: "json",
			data: {
				"userName": usr,
				"userPwd": pwd,
			}
		}, function(e) {
			$('.alert-danger', $('.login-form')).hide();

			if(e.userInfo.length == 1 && _skip) { //如果用户数为1且选择跳过，不弹出选择页，直接登录
				submitLogin(e.userInfo[0]);
			} else { //否则，弹出选择页面，选择后登录
				var selectformHTML = "<br/>";
				$.each(e.userInfo, function(i, user) {
					//存入hashmap以便后面提取
					vw_static.hashMap.Set(user.userID, user);
					//动态生成页面选择列表
					selectformHTML += "<button type='button' class='btn green uppercase btn-block' " +
						"onclick='selectuser(\"" + user.userID + "\")'>" +
						user.userProject +
						"</button>";
				});
				selectformHTML += "<br/><br/>";

				$("#user_info").html(selectformHTML);
				$(".login-form").hide();
				$("#selectUser").show();
			}
		}, function(msg) {
			vw_static.delCookie("remember");
			hascookie = false;
			$('#vw-loginerror').text(msg);
			$('.alert-danger', $('.login-form')).show();
		});
	};

	//验证成功后页面跳转
	function submitLogin(item) {
		//将用户信息存入Cookie，用|区分
		var str = item.userName + "|" + item.userProject + "|" + item.userCode + "|" + item.backToMain + "|" + item.email;
		vw_static.setCookie(window.location.host, item.userID, "8h");
		vw_static.setCookie(item.userID, str, "8h");
		//若记住密码且成功登录，则存入Cookie
		if($("#check-remember").prop("checked")) {
			vw_static.setCookie("remember", usr + "|" + pwd, "7d");
		}
		//根据登录的用户设置其他接口的IP地址
		VW_INTERFACE.WEBSERVICE.setIP(item.serviceIP);
		//跳转到
		var url = item.url.split('/')[3];
		window.location.href = url;
	};

	//通过邮箱重置密码
	function ResetPwd(email) {
		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.LoginManage("ResetPwd"),
			type: "POST",
			dataType: "json",
			data: {
				"email": email
			}
		}, function() {
			$('.alert-reset-ok', $('.forget-form')).show();
		}, function() {
			$('.alert-reset-error', $('.forget-form')).show();
		});
	}

	//注册新用户
	function registUser(userName, userPwd, email) {
		var data = {
			userName: userName,
			userPwd: hex_md5(userPwd),
			email: email
		};

		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.LoginManage("UserRegister"),
			type: "POST",
			dataType: "json",
			data: {
				user: JSON.stringify(data)
			}
		}, function() {
			$('.alert-register-ok', $('.register-form')).show();
		}, function() {
			$('.alert-register-error', $('.register-form')).show();
		});
	}
})